package code.oldCode.classic150;

import utils.TreeNode;

import java.util.Stack;

/**
 * @author cuihaoran
 * @date 2025/1/9
 */
public class Classic150_binarySearchTree {

    /* 530. 二叉搜索树的最小绝对差 */
    int ans = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        // [236,104,701,null,227,null,911]
        //              236
        //      104             701
        // x        227     x       911
        if (root == null)
            return -1;
        dfsGetMin(root);
        return ans;
    }

    private void dfsGetMin(TreeNode root) {
        if (root.left != null) {
            // 左面找最大的节点
            TreeNode leftRightest = root.left;
            while (leftRightest.right != null) {
                leftRightest = leftRightest.right;
            }
            ans = Math.min(ans, root.val - leftRightest.val);
            dfsGetMin(root.left);
        }
        if (root.right != null) {
            // 右面找最小的节点
            TreeNode rightLeftest = root.right;
            while (rightLeftest.left != null) {
                rightLeftest = rightLeftest.left;
            }
            ans = Math.min(ans, rightLeftest.val - root.val);
            dfsGetMin(root.right);
        }
    }

    /* 230. 二叉搜索树中第 K 小的元素 */
    public int kthSmallest(TreeNode root, int k) {
        if (root == null)
            return -1;
        int pos = 0;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();
            pos++;
            if (pos == k) {
                break;
            }
            node = node.right;
        }
        return node.val;
    }

    /* 98. 验证二叉搜索树 */
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        long pre = Long.MIN_VALUE;
        while (!stack.isEmpty() || node != null) {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            node =stack.pop();
            if (node.val <= pre)
                return false;
            pre = node.val;
            node = node.right;
        }
        return true;
    }

    public static void main(String[] args) {

    }
}
